package com.ruoyi.web.ydz.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.ydz.domain.CaseFile;
import com.ruoyi.web.ydz.mapper.CaseFileMapper;
import com.ruoyi.web.ydz.service.ICaseFileService;
import com.ruoyi.web.ydz.util.generatePDF.CreatePdfEchrtsAndTableMain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 病例档案管理Service业务层处理
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class CaseFileServiceImpl implements ICaseFileService {
    @Resource
    private CaseFileMapper caseFileMapper;

    @Resource
    private AttachFileServiceImpl attachFileService;

    @Resource
    private CreatePdfEchrtsAndTableMain createPdfEchrtsAndTableMain;

    @Value("${ruoyi.profile}")
    private String profile;
    /**
     * 查询病例档案管理
     *
     * @param id 病例档案管理主键
     * @return 病例档案管理
     */
    @Override
    public CaseFile selectCaseFileById(Long id) {
        return caseFileMapper.selectCaseFileById(id);
    }

    /**
     * 查询病例档案管理列表
     *
     * @param caseFile 病例档案管理
     * @return 病例档案管理
     */
    @Override
    public List<CaseFile> selectCaseFileList(CaseFile caseFile) {
        /*
         * 如果当前用户身份不是管理员
         * 则查询自身的用药提醒
         * */
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        if (!Objects.isNull(roles)) {
            roles.forEach(bean -> {
                if (100 == bean.getRoleId().longValue()) {
                    caseFile.setCreateBy(String.valueOf(user.getUserId()));
                }
            });
        } else {
            caseFile.setCreateBy(String.valueOf(user.getUserId()));
        }

        return caseFileMapper.selectCaseFileList(caseFile);
    }

    /**
     * 新增病例档案管理
     *
     * @param caseFile 病例档案管理
     * @return 结果
     */
    @Override
    public int insertCaseFile(CaseFile caseFile) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        caseFile.setCreateTime(DateUtils.getNowDate());
        caseFile.setCreateBy(String.valueOf(user.getUserId()));
        caseFile.setCreateName(user.getNickName());

        int i = caseFileMapper.insertCaseFile(caseFile);

        if (!Objects.isNull(caseFile.getAttachFiles())) {
            caseFile.getAttachFiles().forEach(bean -> {
                bean.setSourceId(caseFile.getId());
                bean.setFileClass("01");
                attachFileService.insertAttachFile(bean);
            });
        }

        return i;
    }

    /**
     * 修改病例档案管理
     *
     * @param caseFile 病例档案管理
     * @return 结果
     */
    @Override
    public int updateCaseFile(CaseFile caseFile) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        caseFile.setUpdateTime(DateUtils.getNowDate());
        caseFile.setUpdateBy(String.valueOf(user.getUserId()));
        caseFile.setUpdateName(user.getNickName());

        if (!Objects.isNull(caseFile.getAttachFiles())) {
            caseFile.getAttachFiles().forEach(bean -> {
                if (!Objects.isNull(bean.getId())) {
                    attachFileService.updateAttachFile(bean);
                } else {
                    bean.setSourceId(caseFile.getId());
                    bean.setFileClass("01");
                    attachFileService.insertAttachFile(bean);
                }
            });
        }
        return caseFileMapper.updateCaseFile(caseFile);
    }

    /**
     * 批量删除病例档案管理
     *
     * @param ids 需要删除的病例档案管理主键
     * @return 结果
     */
    @Override
    public int deleteCaseFileByIds(Long[] ids) {
        return caseFileMapper.deleteCaseFileByIds(ids);
    }

    /**
     * 删除病例档案管理信息
     *
     * @param id 病例档案管理主键
     * @return 结果
     */
    @Override
    public int deleteCaseFileById(Long id) {
        return caseFileMapper.deleteCaseFileById(id);
    }

    /*
     * 病例档案导出PDF
     * */
    @Override
    public void exportPDF(HttpServletRequest request, HttpServletResponse response, CaseFile caseFile) {
        if (!Objects.isNull(caseFile.getId())) {
            CaseFile casefile = caseFileMapper.selectCaseFileById(caseFile.getId());
            if (!Objects.isNull(casefile) && !Objects.isNull(casefile.getAttachFiles())) {

                List<String> urls = casefile.getAttachFiles().stream()
                        .filter(file -> "01".equals(file.getFileClass()))  // 过滤 fileClass 为 "01" 的 AttachFile
                        .map(file -> {
                            String url = file.getUrl();
                            if (StringUtils.isNotEmpty(url) && url.startsWith("/profile")) {
                                return profile + url.substring("/profile".length());
                            }
                            return url;
                        })
                        .collect(Collectors.toList());

                if (!Objects.isNull(urls) && urls.size() > 0){
                    createPdfEchrtsAndTableMain.ImageToPDF(urls,request,response);
                }
            }
        }
    }
}
